//
//  EditingViewController.m
//  We_Travel
//
//  Created by lanou3g on 15/12/16.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "EditingViewController.h"
#import "Address.h"
#import "EditingCell.h"
#import "Destination.h"
#import "choiceDayViewController.h"
#import "StartCityTableViewController.h"
#import "MapViewController.h"
#import "CompleteItineratyController.h"
#import "CoreDataToolHelper.h"
#import "AddDestinationTableViewController.h"
#import "DestinationManager.h"
#import "SiteManager.h"
#import "Place.h"
#import "Area.h"
#import "Country.h"
#import "url.h"
@interface EditingViewController ()<UITableViewDataSource,UITableViewDelegate,BMKMapViewDelegate>
@property (nonatomic , strong) Address *address;

@property (nonatomic , strong) UIButton *completeBtn;
@property (nonatomic , strong) UIWindow *window;

@property (nonatomic,strong) NSString *startPlace;
@property (nonatomic,strong) NSString *stopPlace;
@property (nonatomic,strong) UILabel *startLabel;
@property (nonatomic,strong) UILabel *stopLabel;

@property (nonatomic,strong) Place *place;
@property (nonatomic,strong) NSArray *areas;

@end

@implementation EditingViewController

- (void)loadView
{
    self.address = [[Address alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.address;
    ;
}
- (void)viewWillAppear:(BOOL)animated{
    [_address.mapView viewWillAppear];
    _address.mapView.delegate = self;
    [self addView];
    [self.address.tableView reloadData];
   
}
- (void)viewWillDisappear:(BOOL)animated{
    [_address.mapView viewWillDisappear];
    _address.mapView.delegate = nil;
    [self.window resignKeyWindow];
    self.window = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.address.tableView.delegate = self;
    self.address.tableView.dataSource = self;
    self.navigationItem.title = @"编辑行程";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(choiceDestination:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"编辑我的行程";

    [self.address.tableView registerNib:[UINib nibWithNibName:@"EditingCell" bundle:nil] forCellReuseIdentifier:@"editing"];
    [self.address.tableView setEditing:YES animated:YES];
    self.place = [[CoreDataToolHelper shareCoreDataTool]fetchPlaceByCount:[SiteManager shareSiteManager].countryCount];
    self.startPlace = self.place.startPlace;
    self.stopPlace = self.place.stopPlace;
    if (![SiteManager shareSiteManager].isNewPushCom) {
        [self fetchCoreData];
    }
}
//获取数据库中数据
- (void)fetchCoreData{
    self.place = [[CoreDataToolHelper shareCoreDataTool]fetchPlaceByCount:[SiteManager shareSiteManager].countryCount];
    self.areas = [[CoreDataToolHelper shareCoreDataTool]fetchAreaByCountryCount:[SiteManager shareSiteManager].countryCount];
    NSMutableArray *areaNames = [NSMutableArray array];
    for (Area *area in self.areas) {
        [areaNames addObject:area.areaName];
    }
    Country *country = [[CoreDataToolHelper shareCoreDataTool]fetchCountryEntityByCount:[SiteManager shareSiteManager].countryCount];
    [[DestinationManager shareDestinationManager]requireData:HT_DestinationUrl idlast:[country.countryID integerValue]];
    [[DestinationManager shareDestinationManager]setResultBlock:^{
        NSMutableArray *arraySelected = [NSMutableArray array];
        for (Destination *d in [DestinationManager shareDestinationManager].destinationArray) {
            if ([areaNames containsObject:d.name]) {
                d.isSelected = YES;
                [arraySelected addObject:d];
            }
        }
        int arcou = (int)arraySelected.count ;
        for (int j = 0; j < areaNames.count; j++) {
            for (int i = 0; i < arcou; i++) {
                Destination *d = arraySelected[i];
                if ([d.name isEqualToString:areaNames[j]]) {
                    [[DestinationManager shareDestinationManager].SelectedDesArray addObject:d];
                }
            }
        }
        [self.address.tableView reloadData];
    }];
}
- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)addView
{
    self.completeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.completeBtn.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
    self.completeBtn.backgroundColor = [UIColor redColor];
    [self.completeBtn setTitle:@"完成" forState:UIControlStateNormal];
    [self.completeBtn addTarget:self action:@selector(completeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds) - 40, self.view.frame.size.width, 40)];
    [self.window setWindowLevel:UIWindowLevelAlert];
    [self.window makeKeyAndVisible];
    [self.window addSubview:self.completeBtn];
    
}

//点击完成按钮
- (void)completeBtnAction:(UIButton *)sender
{
    if ([DestinationManager shareDestinationManager].SelectedDesArray.count<= 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"小提示：" message:@"请先选择目的地" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        if ([SiteManager shareSiteManager].isNewPushCom) {
            [[CoreDataToolHelper shareCoreDataTool]deleteTravelAreaAllCountryCount:[SiteManager shareSiteManager].countryCount];
            for (Destination *de in [DestinationManager shareDestinationManager].SelectedDesArray) {
                [[CoreDataToolHelper shareCoreDataTool]addTravelAreaName:de.name AreaID:de.ID areaDay:3 CountryCount:[SiteManager shareSiteManager].countryCount];
            }
        }else{
            NSMutableArray *areaNames = [NSMutableArray array];
            for (Area *area in self.areas) {
                [areaNames addObject:area.areaName];
            }
            for (Destination *de in [DestinationManager shareDestinationManager].SelectedDesArray) {
                if (![areaNames containsObject:de.name]) {
                     [[CoreDataToolHelper shareCoreDataTool]addTravelAreaName:de.name AreaID:de.ID areaDay:3 CountryCount:[SiteManager shareSiteManager].countryCount];
                
                }
            }
             NSMutableArray *areaNames2 = [NSMutableArray array];
            for (Destination *de in [DestinationManager shareDestinationManager].SelectedDesArray) {
                 [areaNames2 addObject:de.name];
            }
            [[CoreDataToolHelper shareCoreDataTool]sortAreaByidArray:areaNames2 CountryCount:[SiteManager shareSiteManager].countryCount];
        }
        [[CoreDataToolHelper shareCoreDataTool]changeStartPlace:self.startPlace StopPlace:self.stopPlace CountryCount:[SiteManager shareSiteManager].countryCount];
        CompleteItineratyController *ciVC = [CompleteItineratyController new];
        [self.navigationController showViewController:ciVC sender:nil];
    }
}
//添加旅行地
- (void)choiceDestination:(UIBarButtonItem *)sender
{
    AddDestinationTableViewController *add = [[AddDestinationTableViewController alloc]init];
    [self.navigationController showViewController:add sender:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"editing";
    EditingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[EditingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
        Destination *des = [DestinationManager shareDestinationManager].SelectedDesArray[indexPath.row];
        cell.nameLabel.text = des.name;
        NSString *str = [NSString stringWithFormat:@"%ld天",des.recommend_days];
        des.days = des.recommend_days;
        [cell.timeButton setTitle:str forState:UIControlStateNormal];
        [cell.timeButton addTarget:self action:@selector(changeTimeAction:) forControlEvents:UIControlEventTouchUpInside];
    des.days  = [cell.timeButton.titleLabel.text integerValue];
   
    NSString *str1 = cell.timeButton.titleLabel.text;
    NSString *sta = @"天";
    [str1 stringByAppendingString:sta];
    [cell.timeButton setTitle:str1 forState:UIControlStateNormal];
    return cell;
}
//选择天数
- (void)changeTimeAction:(UIButton *)sender
{
    choiceDayViewController *choiceControl = [choiceDayViewController new];
    choiceControl.block = ^(NSString *string){
        [sender setTitle:string forState:UIControlStateNormal];
    };
    [self presentViewController:choiceControl animated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return [DestinationManager shareDestinationManager].SelectedDesArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 15, 30, 30)];
    imageview.image = [UIImage imageNamed:@"xiajiang.png"];
    [view addSubview:imageview];
    self.stopLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 15, 100, 30)];
    self.stopLabel.text = self.stopPlace;
    [view addSubview:self.stopLabel];
    view.backgroundColor = [UIColor colorWithRed:100 green:127 blue:127 alpha:1];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endAction:)];
    [view addGestureRecognizer:tap];
    return view;
}
//选择结束地
- (void)endAction:(UITapGestureRecognizer *)sender
{
    StartCityTableViewController *start = [StartCityTableViewController new];
    start.block = ^(NSString *string){
        self.stopLabel.text = string;
        self.stopPlace = string;
    };
    start.str = @"结束";
    [self.navigationController pushViewController:start animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 15, 30, 30)];
    imageview.image = [UIImage imageNamed:@"qifei.png"];
    [view addSubview:imageview];
   self.startLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 15, 100, 30)];
    self.startLabel.text = self.startPlace;
    view.backgroundColor = [UIColor colorWithRed:100 green:127 blue:127 alpha:1];
    [view addSubview:self.startLabel];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choiceStart:)];
    [view addGestureRecognizer:tap];
    return view;
}
//选择出发地
- (void)choiceStart:(UITapGestureRecognizer *)sender
{
    StartCityTableViewController *start = [StartCityTableViewController new];
    start.block = ^(NSString *string){
        self.startLabel.text = string;
        self.startPlace = string;
    };
    start.str = @"起始";
    [self.navigationController pushViewController:start animated:YES];
}
#pragma mark 编辑tableView
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (Destination *des in [DestinationManager shareDestinationManager].destinationArray) {
        if (des == [DestinationManager shareDestinationManager].SelectedDesArray[indexPath.row] ) {
            des.isSelected = NO;
        }
    }
    [[DestinationManager shareDestinationManager].SelectedDesArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    [[DestinationManager shareDestinationManager].SelectedDesArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
     [self.address.tableView reloadData];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
